package clw.toy;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chengliwei
 */
public class ToyInstance {

    private ToyClass clazz;
    private final Map<String, Object> fields = new HashMap<>();

    ToyInstance(ToyClass clazz) {
        this.clazz = clazz;
    }


    public Object get(Token name) {
        if (fields.containsKey(name.lexeme)) {
            return fields.get(name.lexeme);
        }

        Function method = clazz.findMethod(name.lexeme);
        if (method != null) return method.bind(this);
        throw new RuntimeError(name, "Undefined property '" + name.lexeme + "'.");
    }

    public void set(Token name, Object value) {
        fields.put(name.lexeme, value);
    }

}
